import fetch from 'dva/fetch';
import {message} from 'antd';

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

function checkCode(json) {
  if (json && json.code) {
    if (json.code != 200) {
      const error = new Error(json.msg);
      error.json = json;
      throw error;
    } else {
      message.success(json.msg);
    }
  }
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default async function request(url, options) {
  let result;
  await fetch(url, options)
    .then(function (response) {
      checkStatus(response);
      return response.json()
    }).then(function (json) {
      checkCode(json);
      result = json.data;
      console.log('parsed json', json)
    }).catch(function (ex) {
      console.log('parsing failed', ex)
    })
  return result;

}
